package demo8;

import demo1.WordCoundJob2;
import demo1.WordCountJob;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class CombinerJob {

    public static void main(String[] args) throws Exception{
        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://hadoop10:9000");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(CombinerJob.class);

        //3. 设置输入格式化工具和输出格式化
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
        TextInputFormat.addInputPath(job, new Path("/mapreduce/demo8/combiner.txt"));
        TextOutputFormat.setOutputPath(job, new Path("/mapreduce/demo8/out"));

//        TextInputFormat.addInputPath(job, new Path(args[0]));
//        TextOutputFormat.setOutputPath(job, new Path(args[1]));
        //5. 设置mapper和reducer
        job.setMapperClass(CombinerMapper.class);
        job.setReducerClass(CombinerReducer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 设置combiner
        job.setCombinerClass(CombinerReducer.class);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b);

    }

    static class CombinerMapper extends Mapper<LongWritable,Text,Text, IntWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] arr = value.toString().split("\t");
            context.write(new Text(arr[0]),new IntWritable(Integer.parseInt(arr[1])));
        }
    }

    static class CombinerReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable v : values) {
                sum += v.get();
            }
            context.write(key,new IntWritable(sum));
        }
    }
}
